package com.ziyougou.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ziyougou.common.to.BoundsTo;
import com.ziyougou.common.to.SkusTo;
import com.ziyougou.product.api.CouponFeign;
import com.ziyougou.product.entity.*;
import com.ziyougou.product.service.*;
import com.ziyougou.product.spuvo.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ziyougou.common.utils.PageUtils;
import com.ziyougou.common.utils.Query;

import com.ziyougou.product.dao.SpuInfoDao;
import org.springframework.util.StringUtils;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Autowired
    private SpuInfoDescService descService;
    @Autowired
    private SpuImagesService spuImagesService;
    @Autowired
    private ProductAttrValueService attrValueService;
    @Autowired
    private AttrService attrService;
    @Autowired
    private SkuInfoService skuInfoService;
    @Autowired
    private SkuImagesService skuImagesService;
    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;
    @Autowired
    private CouponFeign couponFeign;
    @Override
    public void saveSpuInfo(SpuSaveVo vo) {
        //1.保存spu_info表数据
        SpuInfoEntity info = new SpuInfoEntity();
        BeanUtils.copyProperties(vo,info);
        info.setCreateTime(new Date());
        info.setUpdateTime(new Date());
        this.baseMapper.insert(info);
        //2.添加spu_info_desc表
        SpuInfoDescEntity descEntity = new SpuInfoDescEntity();
        descEntity.setSpuId(info.getId());
        List<String> voDecriptList = vo.getDecript();
        descEntity.setDecript(String.join(",",voDecriptList));
        descService.save(descEntity);
        //3.添加spu_images表
        List<String> imagesList = vo.getImages();
        if(imagesList!=null&&imagesList.size()>0){
            spuImagesService.saveImages(info.getId(),imagesList);
        }
        //4.添加product_attr_value
        List<BaseAttrs> baseAttrsList = vo.getBaseAttrs();
        if(baseAttrsList!=null&&baseAttrsList.size()>0){
            List<ProductAttrValueEntity> entityList=baseAttrsList.stream().map(attr->{
                ProductAttrValueEntity productAttrValue = new ProductAttrValueEntity();
                productAttrValue.setSpuId(info.getId());
                productAttrValue.setAttrId(attr.getAttrId().longValue());
                productAttrValue.setAttrValue(attr.getAttrValues());
                productAttrValue.setQuickShow(attr.getShowDesc());
                //设置属性名
                AttrEntity attrEntity = attrService.getById(attr.getAttrId());
                productAttrValue.setAttrName(attrEntity.getAttrName());
                return productAttrValue;
            }).collect(Collectors.toList());
            attrValueService.saveBatch(entityList);
        }
        //5.保存sku的信息
        List<Skus> skusList = vo.getSkus();
        if(skusList!=null&&skusList.size()>0){
            for (Skus skus : skusList) {
                //5.1 保存sku_info表
                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                skuInfoEntity.setSpuId(info.getId());
                skuInfoEntity.setSkuName(skus.getSkuName());
                skuInfoEntity.setSkuDesc(null);
                skuInfoEntity.setCatalogId(info.getCatalogId());
                skuInfoEntity.setBrandId(info.getBrandId());
                List<Images> skusImages = skus.getImages();
                String url="";
                for (Images skusImage : skusImages) {
                    if(skusImage.getDefaultImg()==1){//前端给定的条件值是，默认图片状态为 1
                        url= skusImage.getImgUrl();
                    }
                }
                skuInfoEntity.setSkuDefaultImg(url);
                skuInfoEntity.setSkuTitle(skus.getSkuTitle());
                skuInfoEntity.setSkuSubtitle(skus.getSkuSubtitle());
                skuInfoEntity.setPrice(new BigDecimal(skus.getPrice()));
                skuInfoEntity.setSaleCount(0L);//销量
                skuInfoService.save(skuInfoEntity);
                //5.2 保存每个sku的图片列表 sku_image表
                List<Images> imagesList2 = skus.getImages();
                List<SkuImagesEntity> imagesEntityList=
                        imagesList2.stream().map(image->{
                            SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                            skuImagesEntity.setSkuId(skuInfoEntity.getSkuId());
                            skuImagesEntity.setImgUrl(image.getImgUrl());
                            skuImagesEntity.setDefaultImg(image.getDefaultImg());
                            return skuImagesEntity;}).collect(Collectors.toList());
                skuImagesService.saveBatch(imagesEntityList);
                //5.3 保存销售属性 : sku_sale_attr_value
                List<Attr> attrList = skus.getAttr();
                List<SkuSaleAttrValueEntity>  saleAttrValueEntitiesList=
                        attrList.stream().map(attr -> {
                            SkuSaleAttrValueEntity skuSaleAttrValueEntity = new SkuSaleAttrValueEntity();
                            skuSaleAttrValueEntity.setSkuId(skuInfoEntity.getSkuId());
                            BeanUtils.copyProperties(attr,skuSaleAttrValueEntity);
                            return skuSaleAttrValueEntity;}).collect(Collectors.toList());
                skuSaleAttrValueService.saveBatch(saleAttrValueEntitiesList);
                //5.4 保存优惠价相关信息: ziyougoumall_sms里的 member_price,sku_full_reduction,sku_ladder
                //调取的模块: coupon模块 -远程调用
                SkusTo skusTo = new SkusTo();
                BeanUtils.copyProperties(skus,skusTo);
                skusTo.setSkuId(skuInfoEntity.getSkuId());
                //远程调用
                couponFeign.saveSkuReduction(skusTo);
            }

        }

        //6.保存积分相关信息: ziyougoumall_sms库中的spu_bounds表
        BoundsTo boundsTo = new BoundsTo();
        boundsTo.setSpuId(info.getId());
        boundsTo.setGrowBounds(vo.getBounds().getGrowBounds());
        boundsTo.setBuyBounds(vo.getBounds().getBuyBounds());
        couponFeign.saveBounds(boundsTo);
    }

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        LambdaQueryWrapper<SpuInfoEntity> wrapper = new LambdaQueryWrapper<>();
        //添加筛选条件
        //1.获取模糊查条件
        String key=(String) params.get("key");
        if(!StringUtils.isEmpty(key)){
            wrapper.like(SpuInfoEntity::getSpuName,key);
        }
        //2.分类id
        String catelogId = (String) params.get("catelogId");
        if(!StringUtils.isEmpty(catelogId)){
            Long cid =Long.parseLong(catelogId);
           if(cid>0){ wrapper.eq(SpuInfoEntity::getCatalogId,cid);}
        }
        //3.品牌id
        String brandId=(String)params.get("brandId");

        if(!StringUtils.isEmpty(brandId)){
            Long bid =Long.parseLong(brandId);
          if(bid>0){  wrapper.eq(SpuInfoEntity::getBrandId,bid);}

        }
        //4.状态
        String status=  (String) params.get("status");

        if(!StringUtils.isEmpty(status)){
            Integer s=Integer.parseInt(status);
            if(s>=0&&s<=2){
                wrapper.eq(SpuInfoEntity::getPublishStatus,s);
            }
        }

        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

}